package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.bzkj.basicinfo.domain.ncc.NccBasicSupplier;
import com.bzkj.basicinfo.domain.ncc.dto.NccBasicSupplierDto;
import com.bzkj.basicinfo.domain.ncc.erp.SupplierBean;
import com.bzkj.basicinfo.mapper.NccBasicSupplierMapper;
import com.bzkj.basicinfo.service.ncc.NccBasicSupplierService;
import com.bzkj.basicinfo.utils.DataBatchProcessorUtil;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.basicinfo.utils.NccBasicUtil;
import com.bzkj.basicinfo.utils.UniqueIdentifierGenerator;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 供应商信息：7
 */
@Service("nccJobSupplierService")
@Slf4j
public class NccBasicSupplierServiceImpl implements NccBasicSupplierService {
    @Autowired
    private NccBasicSupplierMapper nccBasicSupplierMapper;
    @Autowired
    private NccBasicUtil nccBasicUtil;
    @Value("${ncc.baseUrl}")
    private static String url;

    @Value("${ncc.basicInfoUrl}")
    private String basicInfoUrl;

    @Value("${ncc.sourceSystem}")
    private static String sourceSystem;

    @Value("${ncc.targetSystem}")
    private static String targetSystem;

    @Value("${ncc.serviceName}")
    private static String serviceName;

    @Value("${ncc.contentType}")
    private static String contentType;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;

    @Autowired
    private UniqueIdentifierGenerator uniq;

    @Override
    public void updateNccBasicSupplierJob(String all) {
        if ("all".equals(all)) {
            nccBasicUtil.ncc(7, pkOrgCode);
        } else {
            HttpResponse response = methodExecute(7);
            if (response.isOk()) {
                String responseBody = response.body();
                JSONObject entries = JSONUtil.parseObj(responseBody);
                JSONArray dataArray = entries.getJSONArray("data");
                List<NccBasicSupplier> basicSuppliers = dataArray.toList(NccBasicSupplier.class);
                for (NccBasicSupplier basicCustomer : basicSuppliers) {
                    NccBasicSupplier basicCustomer1 = nccBasicSupplierMapper.queryNccBasicSupplier(basicCustomer.getCode());
                    if (basicCustomer1 != null) {
                        nccBasicSupplierMapper.updateNccBasicSupplier(basicCustomer);
                    } else {
                        nccBasicSupplierMapper.insertNccBasicSupplier(basicCustomer);
                    }
                }
            }
        }
    }

    /**
     * 修改供应商状态
     *
     * @Author wangzhichao
     * @Date 2024/12/05 15:43:15
     * @Param status 状态
     * @Param pkSupplier 主键
     */
    @Override
    public AjaxResult nccBasicSupplierEnableStatusUpdate(String status, String pkSupplier) {
        String userName = SecurityUtils.getLoginUser().getUser().getUserName();
        try {
            int i = nccBasicSupplierMapper.nccBasicSupplierEnableStatusUpdate(status, pkSupplier, userName);
            return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("未找到指定数据");
        } catch (Exception e) {
            log.error("修改失败:" + e);
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 修改供应商数据
     *
     * @param entity
     * @Author wangzhichao
     * @Date 2024/12/05 16:04:34
     */
    @Override
    public AjaxResult nccBasicSupplierUpdate(NccBasicSupplier entity) {
        try {
            NccBasicSupplier supplier = nccBasicSupplierMapper.queryNccBasicSupplier(entity.getCode());
            entity.setModifier(SecurityUtils.getLoginUser().getUser().getUserName());
            if (Objects.isNull(supplier)) {
                int i = nccBasicSupplierMapper.nccBasicSupplierUpdate(entity);
                return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("未找到指定数据");
            } else {
                if ((entity.getPkSupplier().equals(supplier.getPkSupplier()))) {
                    nccBasicSupplierMapper.nccBasicSupplierUpdate(entity);
                    return AjaxResult.success("修改成功");
                } else {
                    return AjaxResult.error("代码重复");
                }
            }
        } catch (Exception e) {
            log.error("修改失败:{}", e);
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 根据条件分页查询供应商信息
     *
     * @Author wangzhichao
     * @Date 2024/12/05 16:57:26
     * @Param dto 查询条件
     * @Param page 分页条件
     */
    @Override
    public List<NccBasicSupplier> nccBasicSupplierFindData(NccBasicSupplierDto dto) {
        // 获取分页数据
        return nccBasicSupplierMapper.nccBasicSupplierFindData(dto);
    }

    /**
     * 新增供应商信息
     *
     * @Author wangzhichao
     * @Date 2024/12/06 09:21:10
     * @Param entity
     */
    @Override
    @Transactional
    public AjaxResult nccBasicSupplierSave(NccBasicSupplier entity) {
        try {
            NccBasicSupplier supplier = nccBasicSupplierMapper.queryNccBasicSupplier(entity.getCode());
            if (Objects.isNull(supplier)) {
                String userName = SecurityUtils.getLoginUser().getUser().getUserName();
                entity.setModifier(userName);
                entity.setModifiedtime(new Date());
                entity.setCreator(userName);
                entity.setCreationtime(new Date());
                entity.setTs(new Date());
                entity.setPK_ORG("0001A1100000000021CH");
                entity.setPK_GROUP("0001A1100000000021CH");
                entity.setSupstate("1");
                entity.setMnecode(getCapitalInitials(entity.getName()));
                synchronized (this) {
                    String pkSupplier = "WMS" + uniq.generateUniqueIdentifier();
                    entity.setPK_SUPPLIER(pkSupplier);
                }
                nccBasicSupplierMapper.insertNccBasicSupplier(entity);
                return AjaxResult.success("保存成功");
            } else {
                return AjaxResult.error("保存失败供应商代码重复");
            }
        } catch (Exception e) {
            log.error("保存失败:{}", e);
            return AjaxResult.error("保存失败");
        }
    }

    @Override
    public List<String> findBaiscSuppleierName(String name) {
        return nccBasicSupplierMapper.findBaiscSuppleierName(name);
    }

    @Autowired
    private HttpClientUtils hcu;

    /**
     * 同步当天供应商信息
     *
     * @return
     */
    @Override
    public AjaxResult jobMethodExecute(Boolean flag) {
        HashMap<String, String> searchDate = DataBatchProcessorUtil.getSearchDate(flag);

        // 查询当前数据
        HttpResponse response = hcu.methodExecute(searchDate.get("startTimeStr"), searchDate.get("endTimeStr"),7, pkOrgCode);
        com.alibaba.fastjson2.JSONObject jsonNode = JSON.parseObject(response.body());
        // 收集rep系统数据
        List<SupplierBean> list = jsonNode.getJSONArray("data").toJavaList(SupplierBean.class);
        if (!list.isEmpty())
            extracted(list);

        return AjaxResult.success("同步成功");
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<SupplierBean> list) {
        for (SupplierBean supplierBean : list) {
            nccBasicSupplierMapper.insertOrUpdate(supplierBean);
        }
    }

    public String getCapitalInitials(String chinese) {
        StringBuilder initials = new StringBuilder();
        char[] chars = chinese.toCharArray();
        for (char ch : chars) {
            if (Character.toString(ch).matches("[\\u4E00-\\u9FA5]")) {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(ch);
                if (pinyinArray != null && pinyinArray.length > 0) {
                    initials.append(pinyinArray[0].substring(0, 1).toUpperCase());
                }
            } else {
                initials.append(ch);
            }
        }
        return initials.toString();
    }

    /**
     * 公有方法抽取
     *
     * @param i
     * @return
     */
    public HttpResponse methodExecute(Integer i) {
        //        String url = NccHttpUtils.getUrl();
        HashMap<String, Object> hashMap = new HashMap<>();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 昨天的00:00
        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        String startOfYesterdayStr = startOfYesterday.format(formatter);
        // 昨天的23:59:59
        LocalDateTime endOfYesterday = yesterday.atTime(23, 59, 59);
        String endOfYesterdayStr = endOfYesterday.format(formatter);
        //        添加post请求参数
        hashMap.put("startTime", startOfYesterdayStr);

        //        hashMap.put("startTime", "2022-01-01 02:32:20");
        hashMap.put("endTime", endOfYesterdayStr);
        hashMap.put("nccBaseDataEnum", i);
        hashMap.put("platformCode", "111");
        String jsonString = JSONUtil.toJsonStr(hashMap);

        // 添加请求头
        HttpResponse response = HttpUtil.createPost(basicInfoUrl).header("sourceSystem", sourceSystem).header("targetSystem", targetSystem).header("serviceName", serviceName).header("contentType", contentType).body(jsonString, "application/json").execute();
        return response;
    }


}
